<template>
  <div style="font-size: 14px">
    <!-- 资产详情弹窗 -->
    <el-drawer v-model="dialogVisible" title="资产详情" direction="rtl" size="1180">
      <div v-loading="loading">
        <div class="title">基本信息</div>
        <div v-if="showCustomerForm == true">
          <form-create v-model="formData" :option="option" :rule="formCreateRules" />
        </div>
        <div v-if="showCustomerForm == false">
          <div class="table-data-box">
            <div class="data-cell">
              <span class="label">资产名称</span>
              <span class="content">{{ details.ciname }}</span>
            </div>
            <div class="data-cell">
              <span class="label">配置项分类</span>
              <div class="content" v-html="details.categoryName"></div>
            </div>
            <div class="data-cell">
              <span class="label">固定资产编号</span>
              <span class="content">{{ details.cino }}</span>
            </div>
            <div class="data-cell">
              <span class="label">所属客户</span>
              <span class="content">{{ details.companyName }}</span>
            </div>
            <div class="data-cell">
              <span class="label">状态</span>
              <div class="content">
                <span
                  v-if="details.statusColor"
                  :style="{ background: details.statusColor }"
                  style="padding: 0 8px; color: #ffffff"
                >
                  {{ details.status }}
                </span>
                <span v-else>{{ details.status }}</span>
              </div>
            </div>
            <div class="data-cell">
              <span class="label">位置</span>
              <span class="content">{{ details.loc }}</span>
            </div>

            <div class="data-cell" v-if="Object.keys(details.attrVals).length > 0">
              <span class="label">ip</span>
              <span class="content">{{ details.attrVals.eav_1737617726179 }}</span>
            </div>
            <div class="data-cell" v-if="Object.keys(details.attrVals).length > 0">
              <span class="label">品牌型号</span>
              <span class="content">{{ details.attrVals.eav_1737617774915 }}</span>
            </div>
            <div class="data-cell" v-if="Object.keys(details.attrVals).length > 0">
              <span class="label">序列号</span>
              <span class="content">{{ details.attrVals.eav_1737617752494 }}</span>
            </div>
            <div class="data-cell" v-if="Object.keys(details.attrVals).length > 0">
              <span class="label">对应部门</span>
              <span class="content">{{ details.attrVals.eav_1737617804408 }}</span>
            </div>

            <div class="data-cell">
              <span class="label">采购日期</span>
              <span class="content">{{ details.buyDate }}</span>
            </div>
            <div class="data-cell">
              <span class="label">到货日期</span>
              <span class="content">{{ details.arrivalDate }}</span>
            </div>
            <div class="data-cell">
              <span class="label">预警日期</span>
              <span class="content">{{ details.warningDate }}</span>
            </div>
            <div class="data-cell">
              <span class="label">生命周期(月)</span>
              <span class="content">{{ details.lifeCycle }}</span>
            </div>
            <div class="data-cell">
              <span class="label">保修期(月)</span>
              <span class="content">{{ details.warranty }}</span>
            </div>
            <div class="data-cell">
              <span class="label">资产原值</span>
              <span class="content">{{ details.assetsOriginalValue }}</span>
            </div>
            <div class="data-cell">
              <span class="label">部门</span>
              <span class="content">{{ details.department }}</span>
            </div>
            <div class="data-cell">
              <span class="label">负责人</span>
              <span class="content">{{ details.owner }}</span>
            </div>
            <div class="data-cell">
              <span class="label">使用人</span>
              <span class="content">{{ details.userName }}</span>
            </div>
            <div class="data-cell">
              <span class="label">折旧年限(年)</span>
              <span class="content">{{ details.depreciationIsZeroYears }}</span>
            </div>
          </div>
        </div>
        <el-tabs v-model="tabName" class="demo-tabs">
          <!-- 附件 -->
          <el-tab-pane label="附件" name="enclosure">
            <EnclosureList :ci-id="details.ciId" event-type="itsm.configureItem" :edit="false"></EnclosureList>
          </el-tab-pane>
          <!-- 关联配置项 -->
          <!-- <el-tab-pane label="关联配置项" name="associationConfig">
            <AssociationConfigList
              v-if="tabHistory.indexOf('associationConfig') >= 0"
              :ci-id="details.ciId"
            ></AssociationConfigList>
          </el-tab-pane> -->
          <!-- 关联服务 -->

          <el-tab-pane label="关联服务" name="associationServe">
            <AssociationServicesBox :list="details.serviceDirDtos || []"></AssociationServicesBox>
          </el-tab-pane>

          <!-- 关联请求 -->
          <div v-auth="'configItem_detail_relatingRequest'">
            <el-tab-pane label="关联请求" name="associationRequest">
              <AssociationRequestBox
                v-if="tabHistory.indexOf('associationRequest') >= 0"
                :ci-id="details.ciId"
              ></AssociationRequestBox>
            </el-tab-pane>
          </div>
          <!-- 关联变更 -->
          <div v-auth="'configItem_detail_relatingChange'">
            <el-tab-pane label="关联变更" name="associationChange">
              <AssociationChange v-if="tabHistory.indexOf('associationChange') >= 0" :ci-id="details.ciId"></AssociationChange>
            </el-tab-pane>
          </div>
          <!-- 关联问题 -->
          <div v-auth="'configItem_detail_relatingProblem'">
            <el-tab-pane label="关联问题" name="associationQuestion">
              <AssociationQuestionList
                v-if="tabHistory.indexOf('associationQuestion') >= 0"
                :ci-id="details.ciId"
              ></AssociationQuestionList>
            </el-tab-pane>
          </div>
          <!-- 历史更新 -->
          <div v-auth="'configItem_detail_historyUpdate'">
            <el-tab-pane label="历史更新" name="historicalUpdates">
              <HistoricalUpdatesList
                v-if="tabHistory.indexOf('historicalUpdates') >= 0"
                :ci-id="details.ciId"
              ></HistoricalUpdatesList>
            </el-tab-pane>
          </div>
          <!-- 二维码 -->
          <!-- <div v-auth="'CONFIGITEM_DETAIL_TDCODE'">
            <el-tab-pane label="二维码" name="qrcodeBox">
              <div v-loading="generateQrcodeLoading">
                <div style="margin-bottom: 15px">
                  <el-button type="primary" :icon="qrcode ? Check : ''" @click="generateQrcode">生成二维码</el-button>
                  <el-button type="primary" v-if="qrcode" @click="downLoadQrcode">下载二维码</el-button>
                </div>
                <div v-if="qrcode">
                  <img :src="qrcode" style="display: block; height: 340px" alt="二维码" />
                </div>
              </div>
            </el-tab-pane>
          </div> -->
          <div v-if="showCustomerForm == true">
            <el-tab-pane :label="item.tabName" :name="item.tabName" v-for="(item, index) in tabList" :key="index">
              <form-create v-model="item.formData" :option="item.option" :rule="item.formCreateRules" />
            </el-tab-pane>
          </div>
        </el-tabs>
      </div>
    </el-drawer>
  </div>
</template>

<script setup lang="ts" name="DetailsMask">
import { ref, watch } from "vue";
import { Check } from "@element-plus/icons-vue";

import EnclosureList from "@/components/EnclosureList/index.vue";
// import AssociationConfigList from "@/components/AssociationConfigList/index.vue";
import AssociationServicesBox from "@/components/AssociationServicesBox/index.vue";
import AssociationRequestBox from "@/components/AssociationRequestBox/index.vue";
import AssociationQuestionList from "@/components/AssociationQuestionList/index.vue";
import AssociationChange from "./AssociationChange.vue";
import HistoricalUpdatesList from "./HistoricalUpdatesList.vue";
import { findById, findImage, saveScan } from "@/api/modules/assetManagement";
import { findFormCustomByCiCategoryNo } from "@/api/modules/systemTools";
import { Base64 } from "js-base64";
import { dataDictionaryItemsfindByCode, getCategoryTreeAllData } from "@/api/modules/dataDictionary";

//自定义表单回显
const showCustomerForm = ref(false);
const formCreateRules = ref<any>([]);
const option = ref({
  submitBtn: false
});
const formData = ref({
  arrivalDate: "",
  assetsOriginalValue: "",
  buyDate: "",
  ciname: "",
  cino: "",
  companyName: "",
  companyNo: "",
  department: "",
  departmentName: "",
  depreciationIsZeroYears: "",
  lifeCycle: "",
  loc: "",
  locId: "",
  owner: "",
  ownerId: "",
  statusId: "",
  userName: "",
  userNameId: "",
  warningDate: "",
  warranty: ""
});

//自定义表单回显结束

//选项卡
export interface tabsObj {
  formCreateRules: any[];
  option: {
    submitBtn: false;
  };
  formData: object;
  tabName: string;
  tabId: string;
}
const tabList = ref<tabsObj[]>([]);

const dialogVisible = ref(false);
const details = ref<any>({});
const loading = ref(false);
const tabName = ref("enclosure");
const tabHistory = ref<string[]>([]); // tab切换历史

const qrcode = ref("");
const generateQrcodeLoading = ref(false);
// 获取二维码
const getQrcodeImg = () => {
  generateQrcodeLoading.value = true;
  findImage(details.value.ciId)
    .then((res: any) => {
      generateQrcodeLoading.value = false;
      if (res) {
        qrcode.value = URL.createObjectURL(res);
      }
    })
    .catch(() => {
      generateQrcodeLoading.value = false;
    });
};
// 生成二维码
const generateQrcode = () => {
  generateQrcodeLoading.value = true;
  saveScan({
    "ciDetailDTO.cino": details.value.cino,
    "ciDetailDTO.ciId": details.value.ciId
  })
    .then(res => {
      getQrcodeImg();
    })
    .catch(() => {
      generateQrcodeLoading.value = false;
    });
};
// 下载二维码
const downLoadQrcode = () => {
  if (qrcode.value) {
    const x = new XMLHttpRequest();
    x.open("GET", qrcode.value, true);
    x.responseType = "blob";
    x.onload = function () {
      const url = window.URL.createObjectURL(x.response);
      const a = document.createElement("a");
      a.href = url;
      a.target = "_blank";
      a.download = details.value.cino + "二维码";
      a.click();
      a.remove();
    };
    x.send();
  } else {
  }
};

// 详情
const getData = () => {
  findById(details.value.ciId)
    .then((res: any) => {
      loading.value = false;
      details.value = {
        ...details.value,
        ...res
      };
      //自定义表单
      findFormCustomByCiCategoryNo(details.value.categoryNo).then(res => {
        if (res != null) {
          loading.value = true;
          showCustomerForm.value = true;
          let formCustomRes = JSON.parse(JSON.stringify(res));
          let yyde = Base64.decode(formCustomRes.formCustomContents); //解密
          console.log(yyde);
          let a = JSON.parse(yyde);
          let formCreateRulesArray: any[] = [];
          for (let i = 0; i < a.length; i++) {
            if (a[i].label != undefined && a[i].label != "") {
              showCustomerForm.value = false;
              break;
            }
            if (a[i].attrdataDictionary != null && a[i].attrdataDictionary != undefined) {
              let optionList = [];
              //优先级priority
              dataDictionaryItemsfindByCode(a[i].attrdataDictionary).then(res => {
                (res as any).forEach(function (element) {
                  // element["label"] = element["dname"];
                  // element["value"] = element["dname"];
                  //optionList.push({label:element["dname"],value:element["dcode"]})
                  a[i]["options"].push({ label: element["dname"], value: element["dcode"] });
                });
              });
            }
            formCreateRulesArray.push(a[i] as any);
          }
          formCreateRules.value = formCreateRulesArray;

          tabList.value = [];
          (formCustomRes.formCustomTabsDtos as any).forEach(item => {
            let newItem = JSON.parse(JSON.stringify(item));
            let yydetabAttrsConent = Base64.decode(newItem.tabAttrsConent); //解密
            let aformCreateRules = JSON.parse(yydetabAttrsConent);
            let tmpformData = {};
            (aformCreateRules as any).forEach(itsmtmp => {
              let newItemitsmtmp = JSON.parse(JSON.stringify(itsmtmp));
              tmpformData[newItemitsmtmp.field] = "";
            });
            tabList.value.push({
              formCreateRules: aformCreateRules,
              option: {
                submitBtn: false
              },
              formData: tmpformData,
              tabName: newItem.tabName,
              tabId: newItem.tabId
            });
          });

          let attrVals = details.value.attrVals == undefined ? {} : details.value.attrVals;
          setTimeout(() => {
            formData.value.arrivalDate = details.value.arrivalDate == undefined ? "" : details.value.arrivalDate;
            formData.value.assetsOriginalValue =
              details.value.assetsOriginalValue == undefined ? "" : details.value.assetsOriginalValue;
            formData.value.buyDate = details.value.buyDate == undefined ? "" : details.value.buyDate;
            formData.value.companyName = details.value.companyName == undefined ? "" : details.value.companyName;
            formData.value.companyNo = details.value.companyNo == undefined ? 1 : details.value.companyNo;
            formData.value.ciname = details.value.ciname == undefined ? "" : details.value.ciname;
            formData.value.cino = details.value.cino == undefined ? "" : details.value.cino;
            formData.value.department = details.value.department == undefined ? "" : details.value.department;
            formData.value.departmentName = details.value.department == undefined ? "" : details.value.department;
            formData.value.depreciationIsZeroYears =
              details.value.depreciationIsZeroYears == undefined ? "" : details.value.depreciationIsZeroYears;
            formData.value.lifeCycle = details.value.lifeCycle == undefined ? "" : details.value.lifeCycle;
            formData.value.loc = details.value.loc == undefined ? "" : details.value.loc;
            formData.value.locId = details.value.locId == undefined ? "" : details.value.locId;
            formData.value.owner = details.value.owner == undefined ? "" : details.value.owner;
            formData.value.ownerId = details.value.ownerId == undefined ? "" : details.value.ownerId;
            formData.value.statusId = details.value.statusId == undefined ? "" : details.value.statusId;
            formData.value.userName = details.value.userName == undefined ? "" : details.value.userName;
            formData.value.userNameId = details.value.userNameId == undefined ? "" : details.value.userNameId;
            formData.value.warningDate = details.value.warningDate == undefined ? "" : details.value.warningDate;
            formData.value.warranty = details.value.warranty == undefined ? "" : details.value.warranty;

            Object.keys(attrVals).forEach(key => {
              Object.keys(formData.value).forEach(key2 => {
                if (`${key}` == `${key2}`) {
                  if (`${attrVals[key]}` == "true") {
                    formData.value[`${key2}`] = true;
                  } else {
                    if (!Number.isNaN(Number(`${attrVals[key]}`))) {
                      console.log("数字");
                      //数字
                      formData.value[`${key2}`] =
                        `${attrVals[key]}` == null || `${attrVals[key]}` == undefined || `${attrVals[key]}` == ""
                          ? ""
                          : parseInt(`${attrVals[key]}`);
                    } else {
                      //非数字
                      formData.value[`${key2}`] = `${attrVals[key]}` == null ? "" : `${attrVals[key]}`;
                    }
                  }
                }
              });
            });

            tabList.value.forEach(tabitem => {
              Object.keys(attrVals).forEach(key => {
                Object.keys(tabitem.formData).forEach(key2 => {
                  if (`${key}` == `${key2}`) {
                    if (`${attrVals[key]}` == "true") {
                      tabitem.formData[`${key2}`] = true;
                    } else {
                      if (!Number.isNaN(Number(`${attrVals[key]}`))) {
                        console.log("数字");
                        console.log(`${attrVals[key]}`);
                        console.log(parseInt(`${attrVals[key]}`));
                        //数字
                        tabitem.formData[`${key2}`] =
                          `${attrVals[key]}` == null || `${attrVals[key]}` == undefined || `${attrVals[key]}` == ""
                            ? ""
                            : parseInt(`${attrVals[key]}`);
                      } else {
                        //非数字
                        tabitem.formData[`${key2}`] = `${attrVals[key]}`;
                      }
                    }
                  }
                });
              });
            });

            loading.value = false;
          }, 1500);
        } else {
          showCustomerForm.value = false;
        }
      });
    })
    .catch(() => {
      loading.value = false;
    });
};

const open = (item: any) => {
  details.value = item;
  tabName.value = "enclosure";
  tabHistory.value = [];
  qrcode.value = "";
  dialogVisible.value = true;
  loading.value = true;
  getData();
};

watch(tabName, val => {
  tabHistory.value.push(val);
  if (val == "qrcodeBox") {
    if (!qrcode.value) {
      getQrcodeImg();
    }
  }
});

defineExpose({
  open
});
</script>

<style lang="scss" scoped>
.title {
  margin-bottom: 10px;
  font-weight: bold;
}
</style>
